package user.fragment;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import com.example.xfengshopping.R;

import user.fragment.OrderAdapter;
import user.fragment.OrderItem;
import utils.TokenUtils;

public class OrderListActivity extends AppCompatActivity {

    private RecyclerView recyclerViewOrders;
    private TextView textViewNoMore;
    private OrderAdapter orderAdapter;
    private final ArrayList<OrderItem> orderItems = new ArrayList<>();
    private static final String TAG = "OrderList";
    // 所有 tab ID 数组
    private final int[] tabIds = {
            R.id.tab_all,
            R.id.tab_unpaid,
            R.id.tab_unconfirmed,
            R.id.tab_unshipped,
            R.id.tab_shipped,
            R.id.tab_completed
    };

    private TextView selectedTab = null; // 当前选中的 tab

    @SuppressLint({"WrongViewCast", "MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_list);

        // 初始化视图组件
        recyclerViewOrders = findViewById(R.id.recyclerViewOrders);
        textViewNoMore = findViewById(R.id.textViewNoMore);

        // 设置 RecyclerView
        orderAdapter = new OrderAdapter(orderItems);
        recyclerViewOrders.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewOrders.setAdapter(orderAdapter);

        // 初始化 Tab 点击事件和默认选中状态
        setupTabs();

        // 默认加载全部订单
        loadAllOrders();
    }

    /**
     * 初始化所有 tab 的点击事件和选中状态
     */
    private void setupTabs() {
        for (int id : tabIds) {
            TextView tab = findViewById(id);
            tab.setOnClickListener(v -> {
                updateTabSelection((TextView) v);
                int status = getTabStatusByTag((String) v.getTag());
                if ("全部".equals(v.getTag())) {
                    loadAllOrders();
                } else {
                    loadOrders(1, status); // 加载指定状态订单
                }
            });
        }

        // 默认选中第一个 tab
        selectedTab = findViewById(R.id.tab_all);
        updateTabSelection(selectedTab);
    }

    /**
     * 更新 Tab 选中样式
     */
    private void updateTabSelection(@NonNull TextView currentTab) {
        if (selectedTab != null) {
            selectedTab.setSelected(false);
        }
        currentTab.setSelected(true);
        selectedTab = currentTab;
    }

    /**
     * 根据 tag 获取对应的订单状态码
     */
    private int getTabStatusByTag(String tag) {
        switch (tag) {
            case "待付款":
                return 0;
            case "待确认":
                return 1;
            case "待发货":
                return 2;
            case "已发货":
                return 3;
            case "交易完成":
                return 4;
            default:
                return -1;
        }
    }

    /**
     * 加载所有状态的订单（合并请求）
     */
    private void loadAllOrders() {
        new Thread(() -> {
            String token = TokenUtils.getToken(this);  // 使用 TokenUtils 获取 token

            if (token.isEmpty()) {
                runOnUiThread(() -> Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show());
                return;
            }

            orderItems.clear(); // 清空旧数据

            try {
                // 请求所有状态的数据（分5次请求，status从0到4）
                for (int status = 0; status <= 4; status++) {
                    URL url = new URL("http://47.99.134.126:28019/api/v1/order?pageNumber=1&status=" + status);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("token", token);

                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        InputStream is = conn.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) > 0) {
                            baos.write(buffer, 0, len);
                        }
                        String response = baos.toString();

                        JSONObject obj = new JSONObject(response);
                        int resultCode = obj.getInt("resultCode");

                        if (resultCode == 200) {
                            JSONArray list = obj.getJSONObject("data").getJSONArray("list");
                            for (int i = 0; i < list.length(); i++) {
                                JSONObject orderObj = list.getJSONObject(i);
                                OrderItem item = OrderItem.fromJson(orderObj);
                                orderItems.add(item);
                            }
                        }
                    }
                }

                // 回到主线程刷新 UI
                runOnUiThread(() -> {
                    orderAdapter.notifyDataSetChanged();
                    textViewNoMore.setVisibility(orderItems.isEmpty() ? View.VISIBLE : View.GONE);
                });

            } catch (Exception e) {
                Log.e("OrderListActivity", "加载全部订单失败：" + e.getMessage());
                runOnUiThread(() -> Toast.makeText(this, "加载失败", Toast.LENGTH_SHORT).show());
            }
        }).start();
    }

    /**
     * 按状态加载订单
     */
    private void loadOrders(int pageNumber, int status) {
        String token = TokenUtils.getToken(this);  // 使用 TokenUtils 获取 token
        Log.e(TAG, "TOKEN: "+token);
        if (token.isEmpty()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread(() -> {
            try {
                URL url = new URL("http://47.99.134.126:28019/api/v1/order?pageNumber=" + pageNumber + "&status=" + status);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("token", token);
                Log.e(TAG, "TOKEN_load: "+token);
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = is.read(buffer)) > 0) {
                        baos.write(buffer, 0, len);
                    }
                    String response = baos.toString();

                    JSONObject obj = new JSONObject(response);
                    int resultCode = obj.getInt("resultCode");

                    runOnUiThread(() -> {
                        orderItems.clear();
                        if (resultCode == 200) {
                            try {
                                JSONArray list = obj.getJSONObject("data").getJSONArray("list");
                                for (int i = 0; i < list.length(); i++) {
                                    JSONObject orderObj = list.getJSONObject(i);
                                    OrderItem item = OrderItem.fromJson(orderObj);
                                    orderItems.add(item);
                                }
                                orderAdapter.notifyDataSetChanged();
                                textViewNoMore.setVisibility(orderItems.isEmpty() ? View.VISIBLE : View.GONE);
                            } catch (JSONException e) {
                                Toast.makeText(OrderListActivity.this, "JSON 解析失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            String message = obj.optString("message", "未知错误");
                            Toast.makeText(OrderListActivity.this, "请求失败：" + message, Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    runOnUiThread(() -> Toast.makeText(OrderListActivity.this, "服务器异常", Toast.LENGTH_SHORT).show());
                }
            } catch (Exception e) {
                Log.e("OrderListActivity", "加载订单失败：" + e.getMessage());
                runOnUiThread(() -> Toast.makeText(OrderListActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());
            }
        }).start();
    }
}
